const Vue = require("vue");
const express = require("express");
const server = express();

const template = require("fs").readFileSync("./index.template.html", "utf-8");

const { createBundleRenderer } = require("vue-server-renderer");

const serverBundle = require("./dist/server/vue-ssr-server-bundle.json");
const clientManifest = require("./dist/client/vue-ssr-client-manifest.json");
const path = require("path");

const renderer = createBundleRenderer(serverBundle, {
  runInNewContext: false, // 推荐
  template, // （可选）页面模板
  clientManifest, // （可选）客户端构建 manifest
});

server.use(express.static("./dist/client", { index: false }));

server.get("*", (req, res) => {
  const context = {
    url: req.url,
    title: "vue-ssr",
    meta: `
  <meta charset="UTF-8">
  <meta name="keyword" content="vue,ssr">
  <meta name="description" content="vue srr demo">
`,
  };
  renderer.renderToString(context, (err, html) => {
    console.log(err)
    if (err) {
      if (err.code === 404) {
        res.status(404).end("Page not found");
      } else {
        res.status(500).end("Internal Server Error");
      }
    } else {
      res.end(html);
    }
  });
});

// server.get("*", (req, res) => {
//   const app = new Vue({
//     data: {
//       url: req.url,
//     },
//     template: `<div>访问的 URL 是： {{ url }}</div>`,
//   });

//   renderer.renderToString(app, context, (err, html) => {
//     if (err) {
//       res.status(500).end("Internal Server Error");
//       return;
//     }
//     res.end(html);
//   });
// });

server.listen(8080);
console.log("http://localhost:8080");
